package demo;

import java.time.LocalDateTime;

import com.aerospike.client.Bin;
import com.aerospike.client.IAerospikeClient;
import com.aerospike.client.Key;
import com.aerospike.client.Record;
import com.aerospike.client.Value;
import com.aerospike.client.policy.WritePolicy;

public class TTLTest2 {
	
	final static String namespace = "ns1";
	final static String dataSetName = "testset";
	final static String bin = "DATA";
	
	public static void main(String[] args) throws Exception {

		IAerospikeClient client = AsClientUtil.getClient();
		System.out.println("client="+client);
		
		
	
		
		System.out.println("namespace="+namespace);
		System.out.println("dataSetName="+dataSetName);
		System.out.println("bin="+bin);

		
		// expiration
		// Record expiration. Also known as ttl (time to live).
		// Seconds record will live before being removed by the server.
		
		// -2: Do not change ttl when record is updated. Supported by Aerospike server versions >= 3.10.1.
		// -1: Never expire. Supported by Aerospike server versions >= 3.1.4.
		// 0: Default to namespace configuration variable "default-ttl" on the server.
		// >0: Actual ttl in seconds.
		
		runTest(client,-2);
		runTest(client,-1);
		runTest(client,0);
		runTest(client,100);

		///
		runTest(client,200);
		
		String key = "ttl_test_200";
		String value = key+"_"+LocalDateTime.now();
		Key k = new Key(namespace, dataSetName, key);
		Bin v = new Bin(bin,Value.get(value));
		WritePolicy policy = new WritePolicy();
		// -2 不修改 ttl
		policy.expiration = -2;
		client.put(policy, k,v);
				
		Record record = client.get(null, k);	
		System.out.println("record=" + record+",TTL="+record.getTimeToLive());
		
		

	}
	
	
	private static void runTest(IAerospikeClient client,int ttl) throws Exception{
		WritePolicy policy = new WritePolicy();
		policy.expiration = ttl;
		String key = "ttl_test_"+ttl;
		String value = key+"_"+LocalDateTime.now();
		Key k = new Key(namespace, dataSetName, key);
		Bin v = new Bin(bin,Value.get(value));
		policy.expiration = ttl;
		client.put(policy, k,v);	
        Record record = client.get(null, k);	
		System.out.println("record=" + record+",TTL="+record.getTimeToLive());
		
		Thread.sleep(2000);
		record = client.get(null, k);	
		System.out.println("record=" + record+",TTL="+record.getTimeToLive());
		System.out.println();

		
	}
	
}
	